/**
 * Created by fangshufeng on 2018/4/22.
 */
import io from 'socket.io-client'
import {
    MOCK_DATA_MSG_,
    _MOCK_MESSAGE_,
    _MOCK_REGIST_DEVICE_,
    _MOCK_SOCKET_CONNECT_,
    _MOCK_USER_SELECT_ENV__
} from './socket.msg.type'

// case 名称
const ENV_CHANGE = 'ENV_CHANGE';
const ADD_ONE_DATA = 'ADD_ONE_DATA';
const SELECT_ONE_DATA = 'SELECT_ONE_DATA';
const ADD_ONE_MOCK_DATA = 'ADD_ONE_MOCK_DATA';
const BIND_SESSIONID = 'BIND_SESSIONID';
const REGIST_SUCCEED = 'REGIST_SUCCEED';
const CLEAR_DATA_LIST = 'CLEAR_DATA_LIST';
const CLEAR__MOCK_DATA_LIST = 'CLEAR__MOCK_DATA_LIST';

const Domain = process.env.NODE_ENV === 'production' ? 'http://192.168.28.131:7778' : 'http://localhost:7778';

/**
 * {
    "config": {
        "data": {
            "password": "d051d170235c6682e334e6a5abd8ebdb",
            "blackBox": "eyJ0b2tlbklkIjoiXC9EY3RTdTJlTDg2TTNCNlBmc3dOeGZuR1NFXC95OUl1YVl4THZVVG5cL1pcL01DSnplejR6d3JGdkxmdDNsWFFZbjBQMTNKT0FENit5SEFyZW9lWXNuQU53PT0iLCJvcyI6ImlPUyIsInByb2ZpbGVUaW1lIjoxOTMsInZlcnNpb24iOiIzLjAuNiJ9",
            "clientType": 0,
            "bizCode": 0,
            "username": "summer_zeng",
            "noncestr": "aaksdldrcrfnylkayaiybnayesmg",
            "signature": "2a2b9f0a379c1df273946653b86c596a",
            "timestamp": "1524636266430",
            "appId": "nono",
            "loginType": 2
            }
         },
        "method": "post",
        "timestamp": "1524636993610",
        "url": "https://m.sit.nonobank.com/feserver/user/login",
        "urlIdentification": "/feserver/user/login",
     },

 "data": {
            "errorCode": "8989",
            "errorMessage": "XXX",
            "succeed": "XXX",
            "data": {}
          }
 "headers": {
        "Accept": "application/json, text/plain, ",
        "Content-Length": "463",
        "Content-Type": "application/json",
        "accept": "*",
        "accept-encoding": "gzip, deflate",
        "accept-language": "zh-Hans-CN;q=1",
        "appbuild": "1",
        "appbundleversion": "1",
        "appid": "1",
        "appname": "nnbk",
        "apptype": "ios",
        "appversion": "6.4.9",
        "authorization": "2206ab24da80902ed7025bc81980de56",
        "comefrom": "MaiZI",
        "connection": "keep-alive",
        "content-length": "463",
        "deviceidentifier": "27BADCAD-AB70-4303-AABE-2B8402D82C75",
        "guid": "dd6a082ba828e65aa8f083c957fdc208",
        "ispinfo": "",
        "latitude": "31.210382",
        "longitude": "121.515377",
        "networktype": "Wifi",
        "originid": "27BADCAD-AB70-4303-AABE-2B8402D82C75",
        "osname": "iOS",
        "osversion": "10.3.2",
        "phonebrand": "apple",
        "phonetype": "iPhone 7 Plus(iPhone9,2)",
        "screenheightpixel": "2208",
        "screenwidthpixel": "1242",
        "terminal": "4",
        "user-agent": "YHB_Prj/6.4.9 (iPhone; iOS 10.3.2; Scale/3.00)",
        "userid": "",
        "version": "6.4.9",
        "x-tingyun-id": "cgWWFpLNVAo;c=2;r=786846658"
    }
 }
 }*/
const initState = {
    current_env_tag: '',
    current_select_data: {},
    data_list: [], //里面数据的格式看上面的数据样例
    mock_data_list: [],//里面数据的格式看上面的数据样例
    socketID: '',
    regist_succeed: false,
    socketObj: undefined,
    select_type: undefined
};

export const app = (state = initState, action) => {
    switch (action.type) {
        case ENV_CHANGE:
            return {...state, ...action.data};
        case ADD_ONE_DATA:
            const tempList = [...state.data_list];
            //给每条数据增加一个唯一的key
            tempList.unshift({...action.data, uniqueID: (new Date()).valueOf()});
            return {...state, data_list: tempList};
        case ADD_ONE_MOCK_DATA:
            const temp_mock_list = [...state.mock_data_list];
            //给每条数据增加一个唯一的key
            temp_mock_list.unshift({...action.data, uniqueID: (new Date()).valueOf()});
            return {...state, mock_data_list: temp_mock_list};
        case SELECT_ONE_DATA:
            return {
                ...state, current_select_data: {...action.data}, select_type: action.payload
            };
        case BIND_SESSIONID:
            return {...state, socketID: action.data.socketID, socket: action.payload};
        case REGIST_SUCCEED:
            return {...state, regist_succeed: action.data.result};
        case CLEAR_DATA_LIST:
            return {
                ...state,
                data_list: [],
                current_select_data: state.select_type === __APP_SELECT_TYPE_ALL_LIST_ ? {} : {...state.current_select_data}
            };
        case CLEAR__MOCK_DATA_LIST:
            return {
                ...state,
                mock_data_list: [],
                current_select_data: state.select_type === __APP_SELECT_TYPE_MOCK_LIST_ ? {} : {...state.current_select_data}
            };
        default:
            return {...state};

    }
};

//actions

//isOtherDomain 是否是新增一个域名
export const addEnvAction = (env) => {
    // console.log(tag,envValue,isOtherDomain);
    return (dispath) => {
        socket.emit(_MOCK_USER_SELECT_ENV__, env);
        dispath({
            type: ENV_CHANGE,
            data: {current_env_tag: env.business + '_' + env.env}
        })
    };
};

let socket = undefined;

export const bind_session = () => {
    const socketID = Math.random().toString(36).slice(2);
    socket = io.connect(Domain);
    return dispatch => {
        socket.on('connect', () => {
            console.log('连接成功会话ID为：', socketID);
            socket.emit(_MOCK_SOCKET_CONNECT_, {
                socketID
            });
            dispatch({
                type: BIND_SESSIONID,
                data: {socketID},
                payload: socket
            });
        });
    }
};

export const registDevice = () => {
    return dispath => {
        socket.on(_MOCK_REGIST_DEVICE_, (succeed) => {
            console.log('设备注册成功');
            dispath({
                type: REGIST_SUCCEED,
                data: {result: succeed}
            });
        });
    }
};

export const messageMonitor = () => {
    return dispath => {
        socket.on(_MOCK_MESSAGE_, (data) => {
            console.log('message', data);
            // let temp = this.state.dataList;
            // temp.unshift(data);
            dispath({
                type: ADD_ONE_DATA,
                data: data
            })
        });
    }
};

//列表
export const clear_data_list = () => {
    return {type: CLEAR_DATA_LIST};
};

/**
 * @type 选中行的类型  选中了所有请求列表赋值 all_list
 *                   选中了mock请求列表赋值 mock_list
 *
 * @Date 2018/4/24.
 */
export const select_one_data = (data, type) => {
    return {type: SELECT_ONE_DATA, payload: type, data};
};

//增加mock数据
export const add_one_mock_data = (dataObj) => {
    const {config, data} = dataObj;
    const {urlIdentification} = config;
    socket.emit(MOCK_DATA_MSG_, {
        mockKey: urlIdentification,
        mockValue: {...data},
    });
    return {type: ADD_ONE_MOCK_DATA, data: dataObj};
};

export const clear_mock_data_list = () => {
    return {type: CLEAR__MOCK_DATA_LIST};
};

// public
//选中的是所有请求的列表
export const __APP_SELECT_TYPE_ALL_LIST_ = 'all_list';
//选中的是mock列表
export const __APP_SELECT_TYPE_MOCK_LIST_ = 'mock_list';